package com.heima.jopo.web;

import com.heima.jopo.mapper.Usermapper;
import com.heima.jopo.obj.UserInfo;
import com.heima.jopo.utilconn.GetConn;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SeleList {


    //查询所有的信息 写入集合中
    public List<UserInfo> listuser() {

        List<UserInfo> userInfos = new ArrayList<UserInfo>();

        //获取JDBC链接
        Connection conn = GetConn.getConn();
        String sql = "select * from t_user_info";

        //查询所有的信息
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet set = ps.executeQuery();

            while (set.next()) {
                String id = set.getString("id");
                String phone = set.getString("phone");
                String passwrod = set.getString("passwrod");
                String username = set.getString("username");
                String sex = set.getString("sex");
                String birthday = set.getString("birthday");
                String career = set.getString("career");

                UserInfo userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setPasswrod(passwrod);
                userInfo.setUsername(username);
                userInfo.setSex(sex);
                userInfo.setBirthday(birthday);
                userInfo.setCareer(career);
                userInfo.setId(id);

                userInfos.add(userInfo);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return userInfos;
    }


    public List<UserInfo> selectUserinfo() {
        //加载mybatis 核心配置文件
        SqlSessionFactory sqlSessionFactory = null;
        SqlSession sqlSession = null;
        InputStream inputStream = null;
        try {
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession();
            //获取接口对象
            Usermapper mapper = sqlSession.getMapper(Usermapper.class);
                                                //执行sql
            List<UserInfo> userInfos = mapper.selectAll();


            return userInfos;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关流
            sqlSession.close();
        }

        return null;
    }
}
